package com.coolwen.hibernate.util;/**
 * Created by CoolWen on 2017/10/29.
 */

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.boot.MetadataSources;

/**
 * @author CoolWen
 * @version 2017-10-29 0:01
 */
public class HibernateUtil {
    private static StandardServiceRegistry standardServiceRegistry;
    private static SessionFactory sessionFactory;

    static {
        if (sessionFactory == null) {
            standardServiceRegistry = new StandardServiceRegistryBuilder().configure().build();
            MetadataSources metadataSource = new MetadataSources(standardServiceRegistry);
            try {
                sessionFactory = metadataSource.buildMetadata().buildSessionFactory();
            } catch (Exception e) {
                e.printStackTrace();
                StandardServiceRegistryBuilder.destroy(standardServiceRegistry);
            }
        }
    }

    public static Session openSession() {
        return sessionFactory.openSession();
    }

    public static void  closeSession(Session session){
        try {
            if (session!=null){
                session.close();
            }
        } catch (HibernateException e) {
            e.printStackTrace();
        }

    }
}
